<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">小区管理</h1>
      <div class="search-container">
        <div class="search-input-group">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入小区名称"
            clearable
            style="width: 300px"
            @input="handleSearch"
          />
        </div>
      </div>
    </div>

    <!-- 小区卡片列表 -->
    <div v-loading="loading" class="community-grid">
      <!-- 现有小区卡片 -->
      <div
        v-for="community in filteredCommunities"
        :key="community.id"
        class="community-card"
      >
        <div class="card-image">
          <div class="image-placeholder">
            <IconifyIconOffline icon="ep:picture" class="placeholder-icon" />
            <span class="placeholder-text">暂无图片</span>
          </div>
        </div>

        <div class="card-content">
          <h3 class="community-name">{{ community.name }}</h3>
          <div class="expiration-info">
            <span class="label">到期时间:</span>
            <span class="value">{{
              formatDate(community.expirationTime)
            }}</span>
          </div>

          <div class="feature-icons">
            <IconifyIconOffline icon="ep:chat-dot-round" class="feature-icon" />
            <IconifyIconOffline icon="ep:money" class="feature-icon" />
            <IconifyIconOffline icon="ep:credit-card" class="feature-icon" />
          </div>
        </div>

        <div class="card-actions">
          <el-button
            class="action-btn"
            type="success"
            size="small"
            @click="handleEdit(community)"
          >
            <IconifyIconOffline icon="ep:edit" />
            编辑
          </el-button>
          <el-button
            class="action-btn"
            type="danger"
            size="small"
            @click="handleDelete(community)"
          >
            <IconifyIconOffline icon="ep:delete" />
            删除
          </el-button>
        </div>
      </div>

      <!-- 添加小区卡片 -->
      <div class="add-community-card" @click="handleAdd">
        <div class="add-icon">
          <IconifyIconOffline icon="ep:plus" />
        </div>
        <div class="add-text">添加小区</div>
        <div class="add-limit">当前还能添加2个小区</div>
      </div>
    </div>

    <!-- 小区表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="小区名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入小区名称" />
        </el-form-item>

        <el-form-item label="小区地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入小区地址" />
        </el-form-item>

        <el-form-item label="到期时间" prop="expirationTime">
          <el-date-picker
            v-model="formData.expirationTime"
            type="datetime"
            placeholder="请选择到期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="余额" prop="balance">
          <el-input-number
            v-model="formData.balance"
            :min="0"
            :precision="2"
            placeholder="请输入余额"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            :loading="submitLoading"
            type="primary"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getCommunityList,
  createCommunity,
  updateCommunity,
  deleteCommunity,
  type CommunityItem,
  type CommunityCreateParams,
  type CommunityUpdateParams
} from "@/api/community";

defineOptions({
  name: "DataCenterCommunity"
});

// 响应式数据
const loading = ref(false);
const communityList = ref<CommunityItem[]>([]);
const searchKeyword = ref("");
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const currentEditId = ref<number | null>(null);

// 表单数据
const formData = reactive<Partial<CommunityItem>>({
  name: "",
  address: "",
  expirationTime: "",
  balance: 0
});

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: "请输入小区名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入小区地址", trigger: "blur" }],
  expirationTime: [
    { required: true, message: "请选择到期时间", trigger: "change" }
  ]
};

const formRef = ref<FormInstance>();

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑小区" : "新增小区"));

const filteredCommunities = computed(() => {
  if (!searchKeyword.value) {
    return communityList.value;
  }
  return communityList.value.filter(community =>
    community.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit"
  });
};

// 获取小区列表
const fetchCommunityList = async () => {
  try {
    loading.value = true;
    const response = await getCommunityList();
    if (response.code === 0) {
      communityList.value = response.data;
    }
  } catch (error) {
    ElMessage.error("获取小区列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  // 搜索逻辑在计算属性中处理
};

// 新增小区
const handleAdd = () => {
  isEdit.value = false;
  currentEditId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑小区
const handleEdit = (community: CommunityItem) => {
  isEdit.value = true;
  currentEditId.value = community.id;
  Object.assign(formData, community);
  dialogVisible.value = true;
};

// 删除小区
const handleDelete = async (community: CommunityItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除小区 "${community.name}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    await deleteCommunity(community.id).then(res => {
      if (res.code === 0) {
        ElMessage.success("删除成功");
        fetchCommunityList();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: "",
    address: "",
    expirationTime: "",
    balance: 0
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (isEdit.value) {
      await updateCommunity({
        id: currentEditId.value!,
        name: formData.name!,
        address: formData.address!,
        expirationTime: formData.expirationTime!,
        balance: formData.balance || 0
      });
      ElMessage.success("编辑成功");
    } else {
      await createCommunity({
        name: formData.name!,
        address: formData.address!,
        expirationTime: formData.expirationTime!,
        balance: formData.balance || 0
      });
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    fetchCommunityList();
  } catch (error) {
    ElMessage.error(isEdit.value ? "编辑失败" : "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCommunityList();
});
</script>

<style scoped>
.main {
  min-height: calc(100vh - 120px);
  padding: 20px;
  padding-bottom: 40px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input-group {
  display: flex;
  align-items: center;
  overflow: hidden;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.search-input-group .el-input {
  border: none;
  box-shadow: none;
}

.search-input-group .el-input .el-input__wrapper {
  border: none;
  border-radius: 0;
  box-shadow: none;
}

.search-button {
  height: 32px;
  padding: 0 12px;
  border: none;
  border-radius: 0;
}

.community-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
  padding-bottom: 20px;
}

.community-card {
  padding: 20px;
  cursor: pointer;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
}

.community-card:hover {
  box-shadow: 0 4px 16px rgb(0 0 0 / 15%);
  transform: translateY(-2px);
}

.card-image {
  margin-bottom: 16px;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 120px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 8px;
}

.placeholder-icon {
  margin-bottom: 8px;
  font-size: 32px;
}

.placeholder-text {
  font-size: 14px;
}

.card-content {
  margin-bottom: 16px;
}

.community-name {
  margin: 0 0 12px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.expiration-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.feature-icons {
  display: flex;
  gap: 12px;
}

.feature-icon {
  font-size: 16px;
  color: #c0c4cc;
}

.card-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-btn {
  flex: 1;
  min-width: 80px;
}

.add-community-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  padding: 40px 20px;
  cursor: pointer;
  background: white;
  border: 2px dashed #dcdfe6;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.add-community-card:hover {
  background-color: #f0f9ff;
  border-color: #409eff;
}

.add-icon {
  margin-bottom: 16px;
  font-size: 48px;
  color: #909399;
}

.add-text {
  margin-bottom: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.add-limit {
  font-size: 12px;
  color: #909399;
}

:deep(.el-button) {
  display: flex;
  gap: 4px;
  align-items: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 确保页面底部有足够的空间，避免被页脚遮挡 */
.main {
  position: relative;
  z-index: 1;
}

/* 为最后一个卡片添加额外的底部间距 */
.community-card:last-child {
  margin-bottom: 20px;
}

/* 确保添加小区卡片也有足够的底部间距 */
.add-community-card {
  margin-bottom: 20px;
}

/* 对话框按钮布局样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  align-items: center;
}
</style>
